package com.burgess.net;

import com.burgess.net.dao.ArticleDao;
import com.burgess.net.model.Article;
import com.burgess.net.model.Author;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;

/**
 * 延迟加载测试案例
 */
public class OneToOneTest2 {

    private SqlSessionFactory sqlSessionFactory;

    @Before
    public void before() throws IOException {
        String resource = "mybatis-config2.xml";
        InputStream resourceAsStream = Resources.getResourceAsStream(resource);
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        resourceAsStream.close();
    }

    @Test
    public void testOne2One2(){
        SqlSession sqlSession = this.sqlSessionFactory.openSession();
        try{
            ArticleDao mapper = sqlSession.getMapper(ArticleDao.class);
            Article article = mapper.findOne(1);

            System.out.println("\narticles info: ");
            System.out.println(article);

            System.out.println("\n延迟加载author字段");
            //通过getter方法触发延迟加载
            Author author = article.getAuthor();
            System.out.println("\narticles info:");
            System.out.println(article);
            System.out.println("\nauthor info:");
            System.out.println(author);

        }catch(Exception e){
            e.printStackTrace();
        }finally {
            sqlSession.close();
        }
    }

}
